package se.ytterman.jpcap.jni;

import java.lang.*;
import java.util.*;
import java.util.regex.*;

import se.ytterman.jpcap.data.ethernet.MACAddress;
import se.ytterman.jpcap.data.ip.IPV4Address;

public class PcapInterface {

    PcapInterface() {
    }

    // getName
    public String getDeviceName() {
	return this.name;
    }

    // getDescription
    public String getDescription() {
	return this.description;
    }

    // getMACAddress
    public MACAddress getMACAddress() {
	return this.macAddress;
    }

    // getIPV4Addresses
    public IPV4Address[] getIPV4Addresses() {
	return this.ipv4Addresses;
    }

    // toString
    public String toString() {
	// Remove description parts within parenthesis and rubbish whitespace
	Pattern p = Pattern.compile("\\(.*\\)|[ \\t\\n\\x0B\\f\\r]{2,}");

	Matcher m = p.matcher(this.description);

	StringBuffer buffer = new StringBuffer();

	while (m.find()) {
	    m.appendReplacement(buffer, "");
	}

	m.appendTail(buffer);

	// Concatenate with MAC address
	String result = "[" + this.name + "] " + buffer.toString() + " (" + this.macAddress + ")";

	// Return the rest
	return result;
    }

    // toDocument
    public String toDocument() {
	StringBuilder builder = new StringBuilder();
	
	builder.append("----------------------------------------------------------\n");
	builder.append(".......Name: " + this.name + "\n");
	builder.append("Description: " + this.description + "\n");
	builder.append("........MAC: " + this.macAddress + "\n");

	if(this.ipv4Addresses.length == 0) {
	    builder.append(".IPADDRRESS: NONE\n");
	}
	else {
	    for(int i = 0; i < this.ipv4Addresses.length; i++)
		builder.append(".IPADDRRESS: " + this.ipv4Addresses[i] + "\n");
	}

	builder.append("----------------------------------------------------------\n");

	String result = builder.toString();
	
	return result;
    }

    // Get socket from interface (native)
    public native synchronized PcapSocket getSocketOnInterface();

    // Device name
    private String name;

    // Device decription
    private String description;

    // Currently used MAC of this interface
    private MACAddress macAddress;

    // Array of assigned IPV4 addresses
    private IPV4Address[] ipv4Addresses;
}
